
from django.core.paginator import Paginator
from django.shortcuts import render
from django.utils import timezone
from django.views import View

from contents.models import GoodsCategory, SKU, SPU, GoodsVisitCount
from django.http import HttpResponseForbidden, JsonResponse
from contents.utils import goodscat
from goods.utils import bread_crumb
from meiduo_mall.utils.response_code import RETCODE
# Create your views here.

# <div class="breadcrumb">
#         <a href="{{ breadcrumb.cat1.url }}">{{ breadcrumb.cat1.name }}</a>
#         <span>></span>
#         <a href="javascript:;">{{ breadcrumb.cat2.name }}</a>
#         <span>></span>
#         <a href="javascript:;">{{ breadcrumb.cat3.name }}</a>
#     </div>
# <li v-for="hot in hots">
#                         <a :href="'/detail/'+hot.id+'/'"><img :src="hot.default_image_url"></a>
#                         <h4><a :href="'/detail/'+hot.id+'/'">[[ hot.name ]]</a></h4>
#                         <div class="price">￥[[ hot.price ]]</div>
#                     </li>
# < div class ="sort_bar" >
#
# < a href = "/list/{{ category.id }}/1/"
# { % if sort == 'default' %}class ="active"{% endif %} > 默认 < / a >
#
# < a href = "/list/{{ category.id }}/1/?sort=price"
# { % if sort == 'price' %}class ="active"{% endif %} > 价格 < / a >
# < a href = "/list/{{ category.id }}/1/?sort=hot" { % if sort == 'hot' %}
# class ="active"{% endif %} > 人气 < / a >
# < / div >

class Goods(View):
    def get(self,request,id,pag_num):
        # 面包屑导航
        breadcrumb,cat3 = bread_crumb(id)
        # 排序
        sort = request.GET.get('sort','default')
        page_skus = SKU.objects.filter(category_id=id, is_launched=True).order_by('creat_time')
        if sort == 'price':
            page_skus = SKU.objects.filter(category_id=id,is_launched=True).order_by('price')
        if sort == 'hot':
            page_skus = SKU.objects.filter(category_id=id,is_launched=True).order_by(('-sales'))
        # 分页显示
        paginator = Paginator(page_skus,5)   # 创建一个对象
        page_skus = paginator.page(pag_num)   #  分页第n页的内容对象
        total_page = paginator.num_pages      # 总页数
        context = {
            'category':cat3,
            'categories':goodscat(),
            'breadcrumb':breadcrumb,

            'sort':sort,
            'page_skus':page_skus,
            'page_num':pag_num,
            'total_page':total_page
        }
        return render(request,'list.html',context)

class GoodsHot(View):
    '''热销排行'''
    def get(self,request,id):
        spu_qs = SKU.objects.filter(category_id=id, is_launched=True).order_by('sales')
        hots = spu_qs[:2]
        hot_list = []
        for hot in hots:
            hot_list.append({
                'id':hot.id,
            'default_image_url':hot.default_image.url,
                'name':hot.name,
                'price':hot.price
            })
        return JsonResponse({'code':RETCODE.OK,'errmsg':'ok','hot_skus':hot_list})
class GoodsDetail(View):
    '''产品详情界面'''
    def get(self,request,id):
        categories = goodscat()
        sku = SKU.objects.get(id=id)
        categoty_id = sku.category_id
        breadcrumb,cat3 = bread_crumb(categoty_id)

        # 得到当前的选项组合：
        sku_spec = sku.specs.all().order_by('id')         #当前商品下的所有规格
        spec_list = []
        for skuspec in sku_spec:
            option = skuspec.option_id      #  当前商品规格下的默认选项
            spec_list.append(option)

        # 得到一个字典包含当前商品spu下的所有规格选项组合
        spu = sku.spu  # 得到当前的spu
        accrunt_all_sku_qs = spu.sku_set.all()  # 得到当前spu所有的sku
        sku_option_dirt = {}   # 得到每个sku的选项组合和对于的sku的id
        for sku_model in accrunt_all_sku_qs:
            sku_model_spec = sku_model.specs.all().order_by('id')
            sku_option_list = []
            for sku_sub_spec in sku_model_spec:
                sku_option = sku_sub_spec.option_id
                sku_option_list.append(sku_option)
            sku_option_dirt[tuple(sku_option_list)] = sku_model.id

        # 修改当前选项中的某一个值，得到可能的结果
        spu_spec = spu.specs.all().order_by('id')     # 得到当前spu下的所有规格
        for index,spec in enumerate(spu_spec):
            sku_model_spec = spec.options.all()
            sku_list = spec_list[:]
            for option in sku_model_spec:
                sku_list[index] = option.id
                sku_id = sku_option_dirt.get(tuple(sku_list))
                option.sku_id = sku_id
            spec.spec_options = sku_model_spec
            # spec_options包含了统一中规格的不同选项类
        # {spec: [{name: '', spec_options: {'sku_id': ''}}]}

        context = {'categories': categories,
                    'breadcrumb':breadcrumb,
                   'sku':sku,
                   'category':cat3,
                   'spu': spu,
                   'spec_qs': spu_spec,
                   }
        return render(request,'detail.html',context)

class GoodsVisit(View):
    '''记录商品访问次数'''
    def post(self,request,id):
        try:
            goods = GoodsCategory.objects.get(id=id)
        except GoodsCategory.DoesNotExist:
            return HttpResponseForbidden('ID不存在')

        date = timezone.now()   #  注意此处的导包
        try:
            goods_visit = GoodsVisitCount.objects.get(category=goods,date=date)
        except:
            goods_visit = GoodsVisitCount(
                category_id = id
            )
        goods_visit.count = goods_visit.count + 1
        goods_visit.save()
        return JsonResponse({'code':RETCODE.OK,'errmsg':'ok'})



